package com.yk.govpro.process;

import com.yk.govpro.model.NoticedetailEntity;
import com.yk.govpro.model.NoticelistEntity;
import com.yk.govpro.service.noticeDetail.api.INoticeDetailCrawlerService;
import com.yk.govpro.service.noticeList.api.INoticeListCrawlerService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.List;

/**
 * Created by zsyoung on 2017/5/25.
 */
@Component("main")
public class Main {
    @Autowired
    private INoticeDetailCrawlerService noticeDetailCrawlerService;
    @Autowired
    private INoticeListCrawlerService noticeListCrawlerService;

    private String noticeListURL = "https://www.cqgp.gov.cn/gwebsite/api/v1/notices/stable?";

    public void process() {

        try {
            saveList();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        saveDetail();
    }

    public void saveDetail() {
        for (int pi = 1; pi < 50; pi++) {
            String page = "pi=" + pi + "&ps=20";
            noticeListURL += page;
            List<String> idList = this.noticeListCrawlerService.getDetailIDList(noticeListURL);
            for (String id : idList) {
                for (JSONObject jsonObject : this.noticeDetailCrawlerService.getNoticeDetail(id)) {
                    List<NoticedetailEntity> entites = this.noticeDetailCrawlerService.transform(jsonObject);
                    for (NoticedetailEntity entity : entites) {
                        entity.setNoticeId(id);
                        this.noticeDetailCrawlerService.saveNoticeDetail(entity);
                    }
                }
            }
            noticeListURL="https://www.cqgp.gov.cn/gwebsite/api/v1/notices/stable?";
        }
    }

    public void saveList() throws ParseException {

        for (int pi = 1; pi < 50; pi++) {
        String page = "pi=" + pi + "&ps=20";
            noticeListURL += page;
            for (JSONObject jsonObject : this.noticeListCrawlerService.getNoticeList(noticeListURL)) {
                List<NoticelistEntity> entities = this.noticeListCrawlerService.transform(jsonObject);
                for (NoticelistEntity entity : entities) {
                    this.noticeListCrawlerService.saveNoticeList(entity);
                }
                   noticeListURL="https://www.cqgp.gov.cn/gwebsite/api/v1/notices/stable?";
            }
        }
    }
}